package soen6441;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.*;
import org.apache.lucene.util.Version;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

class IndexDir {
    public static void main(String[] args) throws IOException {
        File dirToIndex = new File(args[0]);
        Directory indexStorage = new SimpleFSDirectory( new File(args[1]));//, new SimpleFSLockFactory() );

        IndexWriter writer = new IndexWriter(indexStorage,
                new StandardAnalyzer(Version.LUCENE_CURRENT),
                true, IndexWriter.MaxFieldLength.LIMITED);
        writer.setUseCompoundFile(false);

        Iterator<File> files = FileUtils.iterateFiles(dirToIndex, null, true);

        while( files.hasNext() ){
            Document doc = new Document();
            File file = files.next();
            FileReader fr = new FileReader(file);
            doc.add( new Field("contents", fr) );
            doc.add( new Field("path", file.getCanonicalPath(),
                    Field.Store.YES,
                    Field.Index.NOT_ANALYZED));
            writer.addDocument(doc);
            fr.close();
        }
        writer.optimize();
        writer.close();
        System.exit(0);
    }
}